package com.atguigu.test01;

import java.util.concurrent.*;
import java.util.function.Consumer;

public class yibubianpai {
    public static void main(String[] args) {
        long l1 = System.currentTimeMillis();
        Mytest mytest = new Mytest();
        //ExecutorService executorService = Executors.newFixedThreadPool(5);
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                3,
                5,
                1,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(10),
                Executors.defaultThreadFactory(),
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
        );
        CompletableFuture<Object> objectCompletableFuture01 = CompletableFuture.supplyAsync(() -> {
            mytest.test1();
            return null;
        }, threadPoolExecutor);

        CompletableFuture<Object> objectCompletableFuture02 = CompletableFuture.supplyAsync(() -> {
            mytest.test2();
            return null;
        }, threadPoolExecutor);

        CompletableFuture<Object> objectCompletableFuture03 = CompletableFuture.supplyAsync(() -> {
            mytest.test3();
            return null;
        }, threadPoolExecutor);


        CompletableFuture<Void> voidCompletableFuture04 = objectCompletableFuture02.thenAcceptAsync(new Consumer<Object>() {
            @Override
            public void accept(Object o) {
                mytest.test2();
            }
        }, threadPoolExecutor);

        CompletableFuture.allOf(objectCompletableFuture01,objectCompletableFuture02,objectCompletableFuture03,voidCompletableFuture04).join();

        threadPoolExecutor.shutdown();

        long l2 = System.currentTimeMillis();
        System.out.println(l2-l1);
    }
}

class Mytest{
    public void test1(){
        try {
            Thread.sleep(100);
            System.out.println(Thread.currentThread().getName()+" 111");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public void test2(){
        try {
            Thread.sleep(200);
            System.out.println(Thread.currentThread().getName()+" 222");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public void test3(){
        try {
            Thread.sleep(300);
            System.out.println(Thread.currentThread().getName()+" 333");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
